package com.ruoyi.wlw.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ruoyi.chart.domain.SpaceLocation;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.wlw.common.ElectricityMeterUtil;
import com.ruoyi.wlw.common.InstructConstant;
import com.ruoyi.wlw.common.InstructTypeConstant;
import com.ruoyi.wlw.domain.IotDevice;
import com.ruoyi.wlw.domain.IotGateway;
import com.ruoyi.wlw.mapper.IotDeviceMapper;
import com.ruoyi.wlw.mapper.IotGatewayMapper;
import com.ruoyi.wlw.service.IotDeviceService;
import com.ruoyi.wlw.service.SendInstructsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 物联设备Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-10
 */
@Service
@Slf4j
public class IotDeviceServiceImpl implements IotDeviceService {
    @Resource
    private IotDeviceMapper iotDeviceMapper;

    @Resource
    private IotGatewayMapper iotGatewayMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SendInstructsService sendInstructsService;

    /**
     * 查询物联设备
     *
     * @param id 物联设备主键
     * @return 物联设备
     */
    @Override
    public IotDevice selectDeviceById(Long id) {
        return iotDeviceMapper.selectDeviceById(id);
    }

    /**
     * 查询物联设备列表
     *
     * @param device 物联设备
     * @return 物联设备
     */
    @Override
    public List<IotDevice> selectDeviceList(IotDevice device) {
        return iotDeviceMapper.selectDeviceList(device);
    }

    /**
     * 新增物联设备
     *
     * @param device 物联设备
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDevice(IotDevice device) {
        device.setCreateBy(SecurityUtils.getUsername());
        device.setCreateTime(DateUtils.getNowDate());
        int rows = iotDeviceMapper.insertDevice(device);
        insertTBaseSpaceLocation(device);
        return rows;
    }

    /**
     * 修改物联设备
     *
     * @param device 物联设备
     * @return 结果
     */
    @Override
    public int updateDevice(IotDevice device) {
        iotDeviceMapper.deleteDeviceById(device.getId());
        insertTBaseSpaceLocation(device);
        return iotDeviceMapper.updateDevice(device);
    }

    /**
     * 批量删除物联设备
     *
     * @param ids 需要删除的物联设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        iotDeviceMapper.deleteDeviceByIds(ids);
        return iotDeviceMapper.deleteDeviceByIds(ids);
    }

    /**
     * 删除物联设备信息
     *
     * @param id 物联设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        iotDeviceMapper.deleteSpaceLocationById(id);
        return iotDeviceMapper.deleteDeviceById(id);
    }

    /**
     * 新增空间位置信息
     *
     * @param iotDevice 水电设备管理对象
     */
    public void insertTBaseSpaceLocation(IotDevice iotDevice) {
        List<SpaceLocation> tBaseSpaceLocationList = iotDevice.getBaseSpaceLocationList();
        Long id = iotDevice.getId();
        if (StringUtils.isNotNull(tBaseSpaceLocationList)) {
            List<SpaceLocation> list = new ArrayList<SpaceLocation>();
            for (SpaceLocation tBaseSpaceLocation : tBaseSpaceLocationList) {
                tBaseSpaceLocation.setId(id);
                list.add(tBaseSpaceLocation);
            }
            if (list.size() > 0) {
                iotDeviceMapper.batchSpaceLocation(list);
            }
        }
    }

    /**
     * 水电开关
     */
    @Override
    public int handlerGateSwitch(Map<String, String> paramMap, HttpServletRequest request) {
        String deviceCode = paramMap.get("deviceCode");
        String type = stringRedisTemplate.opsForValue().get(InstructConstant.handleInstructs + deviceCode);
        if (!StringUtils.isEmpty(type)) {
            throw new RuntimeException("请稍后再试");
        }
        //水表开关阀门状态 1-开 0-关
        String waterStatus = paramMap.get("waterStatus");
        //读表数据
        String waterInfo = paramMap.get("waterInfo");

        //电表总闸开关
        String electricityStatus = paramMap.get("electricityStatus");
        //电表A路闸开关
        String electricityAStatus = paramMap.get("electricityAStatus");
        //电表B路闸开关
        String electricityBStatus = paramMap.get("electricityBStatus");
        //网关信息
        String gatewayId = paramMap.get("gatewayId");
        IotGateway gatewayVO = iotGatewayMapper.selectGatewayById(Long.valueOf(gatewayId));
        if (!StringUtils.isEmpty(waterStatus)) {
            //水闸开关操作
            sendWaterStatus(waterStatus, deviceCode, gatewayVO, request);
        }
        if (!StringUtils.isEmpty(waterInfo)) {
            //水表信息
            sendWaterReadInfo(deviceCode, gatewayVO, request);
        }
        if (!StringUtils.isEmpty(electricityStatus)) {
            //电表总闸操作
            sendElectricityStatus(electricityStatus, deviceCode, gatewayVO, request);
        }
        if (!StringUtils.isEmpty(electricityAStatus)) {
            //电表A闸操作
            sendElectricityAStatus(electricityAStatus, deviceCode, gatewayVO, request);
        }
        if (!StringUtils.isEmpty(electricityBStatus)) {
            //电表B闸操作
            sendElectricityBStatus(electricityBStatus, deviceCode, gatewayVO, request);
        }
        return 1;
    }

    //电表B闸操作
    private void sendElectricityBStatus(String status, String deviceCode, IotGateway gatewayVO, HttpServletRequest request) {
        System.out.println("电表B闸操作");
        String address = "";
        String instruce = "";
        String newIp = "";
        address = ElectricityMeterUtil.deviceAddressConvert(deviceCode);
        newIp = "/" + gatewayVO.getGatewayIp() + ":" + gatewayVO.getGatewayPort();
        if ("1".equals(status)) {
            //合闸
            instruce = ElectricityMeterUtil.getCompleteInstruct(address,
                    InstructConstant.ELECTRICITY_METER_B_NO_INSTRUCT);
            //获取发送指令
            sendInstructsService.sendInstructs(instruce, newIp, request, deviceCode, InstructTypeConstant.E_B_GATE_NO.getKey());
        } else {
            //拉闸
            instruce = ElectricityMeterUtil.getCompleteInstruct(address,
                    InstructConstant.ELECTRICITY_METER_B_PULL_INSTRUCT);
            //获取发送指令
            sendInstructsService.sendInstructs(instruce, newIp, request, deviceCode, InstructTypeConstant.E_B_GATE_OFF.getKey());
        }
    }

    //电表A闸操作
    private void sendElectricityAStatus(String status, String deviceCode, IotGateway gatewayVO, HttpServletRequest request) {
        System.out.println("电表A闸操作");
        String address = "";
        String instruce = "";
        String newIp = "";
        address = ElectricityMeterUtil.deviceAddressConvert(deviceCode);
        newIp = "/" + gatewayVO.getGatewayIp() + ":" + gatewayVO.getGatewayPort();
        if ("1".equals(status)) { //合闸
            instruce = ElectricityMeterUtil.getCompleteInstruct(address,
                    InstructConstant.ELECTRICITY_METER_A_NO_INSTRUCT);
            //获取发送指令
            sendInstructsService.sendInstructs(instruce, newIp, request, deviceCode, InstructTypeConstant.E_A_GATE_NO.getKey());
        } else {//拉闸
            instruce = ElectricityMeterUtil.getCompleteInstruct(address,
                    InstructConstant.ELECTRICITY_METER_A_PULL_INSTRUCT);
            //获取发送指令
            sendInstructsService.sendInstructs(instruce, newIp, request, deviceCode, InstructTypeConstant.E_A_GATE_OFF.getKey());
        }
    }

    //电表总闸操作
    private void sendElectricityStatus(String status, String deviceCode, IotGateway gatewayVO, HttpServletRequest request) {
        System.out.println("电表总闸操作");
        String address = "";
        String instruce = "";
        String newIp = "";
        address = ElectricityMeterUtil.deviceAddressConvert(deviceCode);
        newIp = "/" + gatewayVO.getGatewayIp() + ":" + gatewayVO.getGatewayPort();
        if ("1".equals(status)) { //合闸
            instruce = ElectricityMeterUtil.getCompleteInstruct(address,
                    InstructConstant.ELECTRICITY_METER_ON_INSTRUCT);
            //获取发送指令
            sendInstructsService.sendInstructs(instruce, newIp, request, deviceCode, InstructTypeConstant.E_MAIN_GATE_NO.getKey());
        } else {//拉闸
            instruce = ElectricityMeterUtil.getCompleteInstruct(address,
                    InstructConstant.ELECTRICITY_METER_PULL_INSTRUCT);
            //获取发送指令
            sendInstructsService.sendInstructs(instruce, newIp, request, deviceCode, InstructTypeConstant.E_MAIN_GATE_OFF.getKey());
        }
    }

    //水闸开关操作
    private void sendWaterStatus(String status, String deviceCode, IotGateway gatewayVO, HttpServletRequest request) {
        System.out.println("水闸开关操作");
        String address = "";
        String instruce = "";
        String newIp = "";
        address = ElectricityMeterUtil.deviceAddressConvert(deviceCode);
        newIp = "/" + gatewayVO.getGatewayIp() + ":" + gatewayVO.getGatewayPort();
        if ("1".equals(status)) { //开阀
            instruce = ElectricityMeterUtil.getCompleteInstruct(address,
                    InstructConstant.WATER_METER_NO);
            //获取发送指令
            sendInstructsService.sendInstructs(instruce, newIp, request, deviceCode, InstructTypeConstant.W_GATE_NO.getKey());
        } else {//关阀
            instruce = ElectricityMeterUtil.getCompleteInstruct(address,
                    InstructConstant.WATER_METER_OFF);
            //获取发送指令
            sendInstructsService.sendInstructs(instruce, newIp, request, deviceCode, InstructTypeConstant.W_GATE_OFF.getKey());
        }
    }

    //水表信息
    private void sendWaterReadInfo(String deviceCode, IotGateway gatewayVO, HttpServletRequest request) {
        System.out.println("水表信息");
    }
}
